package memberdao

import (
	"yundian/internel/app/helper/resphelper/memberresp"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
)

func (d *MemberDao) GetWifiMemberInfoByOpenidAndAppId(openid, appId string) *dingo.ErrorWrap {
	m := &memberresp.MemberWithWifiUser{}
	sql := "select * from members m LEFT JOIN wifi_user wu ON m.id = wu.member_id where xcx_openid = ? and app_id = ? limit 1"
	//sql := "select * from members where xcx_openid = ? and app_id = ? limit 1"
	db := global.Orm.Debug().Raw(sql, openid, appId).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

func (d *MemberDao) GetWifiUserInfoByMemberId(memberId int) *dingo.ErrorWrap {
	m := &users.WifiUserDetail{}
	//sql := "select wu.* from wifi_user wu LEFT JOIN users u ON wu.user_id = u.id where wu.member_id = ? limit 1"
	sql := `SELECT wu.id,m.id member_id,u.id user_id,IFNULL(wu.is_admin,u.is_admin)is_admin,IFNULL(wu.profit_proportion,
	u.profit_proportion)profit_proportion,IFNULL(wu.is_divinds,u.is_divinds)is_divinds,u.parent_id,m.headimgurl,m.nick_name FROM members m LEFT JOIN users u ON m.phone=u.phone
	LEFT JOIN wifi_user wu ON wu.user_id=u.id WHERE m.id = ? ORDER BY m.id DESC LIMIT 1`
	db := global.Orm.Raw(sql, memberId).Find(m)
	return dingo.ErrorIf(db.Error, m)
}

//func (d *MemberDao) GetWifiUserInfoByUserId(userId int) *dingo.ErrorWrap {
//	m := &users.WifiUserDetail{}
//	sql := "select wu.* from wifi_user wu LEFT JOIN users u ON wu.user_id = u.id where wu.user_id = ? limit 1"
//	db := global.Orm.Raw(sql, userId).Find(m)
//	return dingo.ErrorIf(db.Error, m)
//}

func (d *MemberDao) GetWifiUserInfoByUserId(userId int) *dingo.ErrorWrap {
	m := &users.WifiUserDetail{}
	sql := `SELECT wu.id,m.id member_id,u.id user_id,IFNULL(wu.is_admin,u.is_admin)is_admin,IFNULL(wu.profit_proportion,
	u.profit_proportion)profit_proportion,IFNULL(wu.is_divinds,u.is_divinds)is_divinds,u.parent_id,u.name,u.user_name,m.headimgurl,m.nick_name FROM members m LEFT JOIN users u ON m.phone=u.phone
	LEFT JOIN wifi_user wu ON wu.user_id=u.id WHERE u.id = ? ORDER BY m.id DESC LIMIT 1`
	db := global.Orm.Raw(sql, userId).Find(m)
	return dingo.ErrorIf(db.Error, m)
}

func (d *MemberDao) UpdateMemberNickName(memberId int, nickname, avatarUrl string) *dingo.ErrorWrap {
	sql := "update members set nick_name = ?, headimgurl = ? where id = ?"
	db := global.Orm.Exec(sql, nickname, avatarUrl, memberId)
	if db.Error != nil {
		return dingo.ErrorIf(db.Error, false)
	}
	return dingo.ErrorIf(db.Error, true)
}

func (d *MemberDao) UpdateWifiUser(memberId, userId, profitProportion int, isAdmin, isDivinds uint8) *dingo.ErrorWrap {
	sql := "update wifi_user set is_admin = ?, is_divinds = ?, profit_proportion = ? where member_id = ? and user_id = ?"
	db := global.Orm.Exec(sql, isAdmin, isDivinds, profitProportion, memberId, userId)
	if db.Error != nil {
		return dingo.ErrorIf(db.Error, false)
	}
	return dingo.ErrorIf(db.Error, true)
}
